package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.dubbo.enums.CommentType;
import com.tanhua.dubbo.pojo.User;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.dubbo.pojo.Video;
import com.tanhua.dubbo.pojo.VideoComment;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.vo.CommentVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.VideoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class VideoService {

    @DubboReference(version = "1.0.0")
    private VideoApi videoApi;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @Autowired
    private VideoMQService videoMQService;

    public Object saveVideo(MultipartFile picFile, MultipartFile videoFile) {
        Long userId = UserThreadLocal.get();

        Video video = new Video();
        video.setUserId(userId);

        //上传图片
        PicUploadResult uploadResult = this.picUploadService.upload(picFile);
        if (StrUtil.isEmpty(uploadResult.getName())) {
            return ErrorResult.builder().errCode("500")
                    .errMessage("上传视频封面图片失败，请重试！").build();
        }

        video.setPicUrl(uploadResult.getName()); //图片

        try {
            //上传小视频
            String fileExtName = StrUtil.subAfter(videoFile.getOriginalFilename(), '.', true);
            StorePath storePath = this.storageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), fileExtName, null);
            video.setVideoUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());
        } catch (Exception e) {
            log.error("上传视频文件失败，userId = {}, file = {}", userId, videoFile.getOriginalFilename(), e);
            return ErrorResult.builder().errCode("501")
                    .errMessage("上传视频文件失败，请重试！").build();
        }

        String videoId = this.videoApi.saveVideo(video);
        if (StrUtil.isEmpty(videoId)) {
            return ErrorResult.builder().errCode("502")
                    .errMessage("保存小视频数据失败，请重试！").build();
        }
        //发送发布成功的消息
        this.videoMQService.videoMsg(videoId);

        return null;
    }

    /**
     * 查询小视频列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryVideoList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        Long userId = UserThreadLocal.get();
        PageInfo<Video> pageInfo = this.videoApi.queryVideoList(userId, page, pageSize);
        List<Video> records = pageInfo.getRecords();

        if (CollUtil.isEmpty(records)) {
            // TODO 给出默认推荐视频 ---完成
            //生效,必须没有推荐视频,数据库没有video 一条数据
            Video video = new Video();
            video.setVideoUrl("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/video/1576134125940400.mp4");
            video.setPicUrl("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/photo/11/1.jpg");
            video.setUserId(userId);
            video.setText("你好啊!");
            video.setLatitude("116.350426");
            video.setLongitude("40.066355");
            video.setLocationName("中国北京市昌平区建材城西路16号");
            this.videoApi.saveVideo(video);
            records=this.videoApi.queryVideoList(userId, page, pageSize).getRecords();
        }

        //查询用户信息
        Map<Long, UserInfo> userInfoMap = this.userInfoApi.queryMapByUserIdList(CollUtil.getFieldValues(records, "userId"));

        List<VideoVo> videoVoList = new ArrayList<>();
        records.forEach(video -> {
            VideoVo videoVo = BeanUtil.toBeanIgnoreError(video, VideoVo.class);
            videoVo.setLikeCount(Convert.toInt(this.videoApi.queryUserCommentCount(video.getId().toHexString(),CommentType.LIKE))); //点赞数
            videoVo.setHasLiked(this.videoApi.queryUserIsLike(userId,video.getId().toHexString())? 1:0);//是否点赞
            videoVo.setHasFocus(this.videoApi.isFollowUser(video.getUserId(),userId)? 1:0); //是否关注
            videoVo.setCommentCount(Convert.toInt(this.videoApi.queryUserCommentCount(video.getId().toHexString(),CommentType.COMMENT))); //评论数
            //查询用户
            UserInfo userInfo = userInfoMap.get(videoVo.getUserId());
            //属性值拷贝
            BeanUtil.copyProperties(userInfo, videoVo, "id", "userId");
            videoVoList.add(videoVo);
        });

        pageResult.setItems(videoVoList);
        return pageResult;
    }

    /**
     * @Author 张园
     * 点赞
     * @param publishId
     * @return 返回点赞数
     */
    public Long likeComment(String publishId) {
        Long userId = UserThreadLocal.get();
        Boolean result=this.videoApi.likeComment(userId,publishId,CommentType.LIKE,null);
        if(result){
           return this.videoApi.queryUserCommentCount(publishId,CommentType.LIKE);  //点赞数
        }
        return null;
    }

    /**
     * @Author 张园
     * 点赞取消
     *
     * @param publishId
     * @return 返回点赞数
     */
    public Long dislikeComment(String publishId) {
        Long userId = UserThreadLocal.get();
        Boolean result=this.videoApi.dislikeComment(userId,publishId,CommentType.LIKE);
        if(result){
            this.videoMQService.likeVideoMsg(publishId);
            return this.videoApi.queryUserCommentCount(publishId,CommentType.LIKE);//点赞数
        }
        return null;
    }

    /**
     * @Author 张园
     * 评论列表
     *
     * @return
     */
    public PageResult queryCommentsList(String videoId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        Long userId = UserThreadLocal.get();

        //查询评论列表数据
        PageInfo<VideoComment> pageInfo = this.videoApi.queryCommentsList(videoId, page, pageSize);
        List<VideoComment> videoCommentList = pageInfo.getRecords();
        if (CollUtil.isEmpty(videoCommentList)) {
            return pageResult;
        }
        //查询发布评论的用户列表数据
        List<Object> userIdList = CollUtil.getFieldValues(videoCommentList, "userId");
        Map<Long, UserInfo> userInfoMap = this.userInfoApi.queryMapByUserIdList(userIdList);

        //封装数据到CommentVoList
        List<CommentVo> commentVos = new ArrayList<>();
        for (VideoComment videoComment : videoCommentList) {
            CommentVo commentVo = new CommentVo();
            commentVo.setId(videoComment.getId().toHexString());
            commentVo.setContent(videoComment.getContent());
            commentVo.setCreateDate(DateUtil.format(new Date(videoComment.getCreated()), "HH:mm:ss"));
            commentVo.setHasLiked(this.videoApi.queryUserIsLike(userId, commentVo.getId()) ? 1 : 0); //用户是否给评论点赞
            commentVo.setLikeCount(Convert.toInt(this.videoApi.queryUserCommentCount(commentVo.getId(), CommentType.COMMENT))); //评论的点赞数
            UserInfo userInfo = userInfoMap.get(videoComment.getUserId());
            commentVo.setAvatar(userInfo.getLogo());
            commentVo.setNickname(userInfo.getNickName());
            commentVos.add(commentVo);
        }
        pageResult.setItems(commentVos);

        return pageResult;
    }


    /**
     * @Author 张园
     * 提交评论
     *
     * @param content comment评论内容
     * @param videoId
     * @return
     */
    public Boolean publishComments(String videoId, String content) {
        if(StrUtil.isEmpty(content)){
            //发布内容为空
            return false;
        }
        Long userId = UserThreadLocal.get();
        return this.videoApi.publishComments(videoId,content,userId);
    }

    /**
     * @Author 张园
     * 关注用户
     *
     * @param userId
     * @return
     */
    public Boolean followUser(Long userId) {
        Long followUserId = UserThreadLocal.get();
        return this.videoApi.followUser(userId, followUserId);
    }

    /**
     * @Author 张园
     * 取消关注用户
     *
     * @param userId
     * @return
     */
    public Boolean disFollowUser(Long userId) {
        Long followUserId = UserThreadLocal.get();
        return this.videoApi.disFollowUser(userId, followUserId);
    }
}
